package com.shop.shop.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.shop.shop.dao.GoodMapper;
import com.shop.shop.model.Good;
import com.shop.shop.model.Order;
import com.shop.shop.util.RedisLock;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.Transaction;

import javax.annotation.Resource;
import java.util.List;

@Service
public class GoodService {
    @Resource
    JedisPool jedisPool;
    @Resource
    GoodMapper goodMapper;
    @Resource
    RedisLock redisLock;

    public List<Good> getAllData() {
        Jedis jedis = jedisPool.getResource();
        if (jedis.exists("allgood")) {
            List<Good> list = JSONArray.parseArray(jedis.get("allgood"), Good.class);
            return list;
        } else {
            List<Good> list = goodMapper.getAllData();
            jedis.set("allgood", JSONObject.toJSONString(list));
            return list;
        }
    }

    public String buy(Long goodID, Integer userId) {
        Integer rest = Integer.valueOf(jedisPool.getResource().hget("restore", goodID.toString()));
        if (rest > 0) {
            String res=redisLock.tryLock(goodID.toString(),String.valueOf(Thread.currentThread().hashCode())+":1","ES",5);
            if ("OK".equals(res)){
                Long restore=goodMapper.getRetore(goodID);
                if (restore>0){
                    //下单成功
                    goodMapper.reduceRestore(restore-1,goodID);
                    redisLock.tryRelease(goodID.toString());
                    /**
                     * @Description:中间添加其他系统功能，如发短信，积分计算等异步功能，考虑使用消息队列
                     * @Param: [goodID, userId]
                     * @returns: java.lang.String
                     * @Author: ypc
                     * @Date: 2021/4/12 16:57
                     * @packageName: com.shop.shop.service
                     */
                    //最简单的队列，lpush()..
                    //
                    return "succeed";
                } else {
                    //数据库库存为0时刷新缓存
                    jedisPool.getResource().hset("restore",goodID.toString(),"0");
                    redisLock.tryRelease(goodID.toString());
                    return "no restore";
                }
            }
        }
        return null;
    }


}
